<?php

namespace app\tools;

use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\Factory;
use app\exception\LogicException;
use app\facade\CurlFacade;
use Carbon\Carbon;
use Exception;
use think\facade\Log;

final class ALiPayTool
{

    /**
     * @return Config
     */
    public function getOptions($notifyUrl = '')
    {
        /** 初始化 **/
        $options = new Config();

        /** 通信协议 **/
        $options->protocol = 'https';

        /** 支付宝网关 **/
        // $options->gatewayHost = 'openapi.alipaydev.com';
        $options->gatewayHost = config('alipay.gateway_host');

        /** 设置签名类型 **/
        $options->signType = 'RSA2';

        /** 应用id,如何获取请参考：https://opensupport.alipay.com/support/helpcenter/190/201602493024 **/
        // $options->appId = '2021000119695999';
        $options->appId = config('alipay.app_id');

        /** 应用私钥, 如何获取请参考：https://opensupport.alipay.com/support/helpcenter/207/201602471154?ant_source=antsupport **/
        // $options->merchantPrivateKey = 'MIIEpAIBAAKCAQEAwd5ws9BDE3YpvZhJGNCebaDjwDXbHchoqg+dUmTa/TkoTyQg9gRBiTBAPl8hTmwOZl4ALWokXgo3cBCw5KF25XOhQpn/PQmhLdqMi/qj+VYLfvulgH7EsNByTQHrhLDkr8AcFK3NXZf3GgmchenPJjjxi9mRFjGC1CpMBMy2KbdakGxnKcI5xecGQYUeRPH7KTlA/ir0H/+Jh+mYvC2rN7ShAOhDhO1U6gnU0TA+keyqxr6TkOll9KTkG1a7icpbQOZO94vTlsOS7Y9FPlI9ucGjc4U0gvpFBt3qxV4cayIE0V124RkNDA7HEISpWsl+TWqy7IBdgYEZDG2b6xXZ/wIDAQABAoIBAHM88ekwpm5vEqisWObzOvkXZcnfOXweoHhWB8HuSW20CA3i/+S86ufNUqLAkV+4Q2b+AUT9jtiHYiSvBzcf8zi43uZj+6AglTpYaqraNZYEW5kDpIEY2XnwrcCwn3qkW4tMumRgW26C4lML24qOTJ//wTTMAr4aeBX9fmpr9OweFFHVw1irhi5nJXvqzCMTUlevYznwAPzh+fN5y2L3ohYXaRj3+lNk6rqgKh7lqwopisY1RED5XZ4WQccxQUiT+ylTqFg9GAB14YbHQ8H5nlRN3WZWFQ0j7nnGgnklX9LxZ+z7M3MP9G1WIZwPxExP6FHeIoaTNtLMg03pC1EZTIECgYEA3wHYZOSAu3irY0J2iyuTG4MjPKhygb/jRwrZwn3Q9enTthZVLcO6YZSxctVxfybDdfIQfPs2zfydApbNqvJjuS2ZF4DCe2aOMjlBG3VSbU7NGi2DLSMsBld/5E2xrc0UlxHABhJ2X196svuaSRLF0G1L2AU2r0FIA2o/ngKNJdECgYEA3o0DevXM7BX/SN4XpJfjlSkcVS6cpKekPsXMDXcy9YJ+Uu2C8zFQZztNkwNX2fE+C4l5rxTwFgOfrxCy9jAqzseG0yF6kEXG6R/qT+RNLAnTsZhQIPSoPNwttbgMlIUSlpTTt/LckE3aWRgxNvWHAA9yEv5G1SQZ6/REzNFzZs8CgYBscH1FMkfW4WqVra/vJJU3/6CW0mI77Y8a8I/LH1sI+VbVaC6rPk3XPXK8IEY8SiEprTePTqjrqTbAF4yS36LWXPHgl9/6GXhzu5uJOpeGR5c8b30l6cBypQGvhogrt1mXzC3PxhKBdfA4MFhpyBMgssT6mi5pMhlOb8/Xie4QwQKBgQCoU537RajONEEXOyxEyMFQ03xjjVLbUxTuiaqx0KORgDbNwGlYScdXnUoqVNAAvu+/yCZqX3rMG8eOoSHLBVmLduyqCltqfexZ7VLLRJF+KpycaejJVGNfTOWh2WhieVg63qxYKG/dEZWB58Npn0GRsR0F8p9enOSiS+oxxIX1jwKBgQCba6AFiy1jqBlBd/3ox8im7hXDsYVyVeoMA68fpu8YXbcZ19fz2Upn9N640TbpPsW0GX4jejgrr3S2TXpmQbQ9tHB4zFtA0FE8Av6aaWGyXIpEYHok8X3dbcU6F4d3FpRYWt3QC9oy+SWMMlPlaTvjeVw/RK4Gk+JLTr3DKwZSEQ==';
        $options->merchantPrivateKey = config('alipay.private_key');

        /** 注:如采用证书模式,无需赋值下面的支付宝公钥字符串 **/
        //$options->alipayCertPath = '<-- 请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt -->';
        //$options->alipayRootCertPath = '<-- 请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt -->';
        //$options->merchantCertPath = '<-- 请填写您的应用公钥证书文件路径，例如：/foo/appCertPublicKey_2019051064521003.crt -->';

        /** 注:如采用非证书模式,则无需赋值上面的三个证书路径,改为赋值如下的支付宝公钥字符串即可 **/
        // $options->alipayPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyS+Re4wal9bUPVnlpo3kp8Y+jWQ8yecpNCNZiu6vqKLAuHw+jyB66CzoXsmPnTwFfslLStU9Vvgt3D2YBBLAroiJY0G4FV/rBxLM8O41KtqIqZCoyhvqwfSdipSw6L/QPvXCe3lOo90JITyf+LWVjJ8exfY551hjwwwHkIjf/BEGT9LxiRX1iYa4zvNmBdxWtk4MDQ2SxDGGa/PVwRlO6YEEHS2KUEUQmJWVs2p0yjJ2KpRCuJ19UxdzIwEtMvA9PPuTQqqe504oBtu5/cveuDkyNW/2MZSWUUc9uXPU6D4YWvWghU6leTVUox+eE6P3MCOrxF9i9j/kwnz2sJv9xQIDAQAB';
        $options->alipayPublicKey = config('alipay.public_key');

        /** 可设置异步通知接收服务地址(可选) **/
        $options->notifyUrl = $notifyUrl;

        /** 可设置AES密钥调用AES加解密相关接口时需要(可选)  **/
        // $options->encryptKey = "pHHVqDDxcRKI/vDcOgy/bw==";
        $encryptKey = config('alipay.encrypt_key');
        if (!empty($encryptKey)) {
            $options->encryptKey = $encryptKey;
        }

        return $options;
    }

    /**
     * APP支付
     * app支付接口2.0
     *
     * @param $params
     * @return false|string
     * @throws LogicException
     */
    public function paymentAppPay($params)
    {
        Factory::setOptions($this->getOptions());
        try {
            $notifyUrl = isset($params['notify_url']) && !empty($params['notify_url']) ? $params['notify_url'] : '';
            $response = Factory::payment()->app()
                ->asyncNotify($notifyUrl)
                ->batchOptional($params['optionalArgs'])
                ->pay($params['subject'], $params['outTradeNo'], $params['totalAmount']);
            return json_encode($response, JSON_UNESCAPED_UNICODE);
        } catch (Exception $e) {
            throw new LogicException($e->getMessage());
        }
    }

    /**
     * APP支付 查询订单
     *
     * @param $outTradeNo
     * @return \Alipay\EasySDK\Payment\Common\Models\AlipayTradeQueryResponse
     * @throws Exception
     */
    public function paymentCommonQuery($outTradeNo)
    {
        Factory::setOptions($this->getOptions());
        $response = Factory::payment()->common()->query($outTradeNo);
        return $response;
    }

    /**
     * 签名验证
     *
     * @param $params
     * @return bool
     */
    public function paymentCommonVerifyNotify($params)
    {
        Factory::setOptions($this->getOptions());
        return Factory::payment()->common()->verifyNotify($params);
    }

    /**
     * 电脑网站支付 debug用
     * alipay.trade.page.pay(统一收单下单并支付页面接口)
     *
     * @param $params
     * @return false|string
     * @throws LogicException
     */
    public function paymentPagePay($params)
    {
        $notifyUrl = isset($params['notify_url']) && !empty($params['notify_url']) ? $params['notify_url'] : '';
        Factory::setOptions($this->getOptions());
        // $response = Factory::payment()->page()->pay($params['subject'], $params['outTradeNo'], $params['totalAmount'], '');
        try {
            $response = Factory::payment()->page()
                ->asyncNotify($notifyUrl)
                ->batchOptional($params['optionalArgs'])
                ->pay($params['subject'], $params['outTradeNo'], '0.01', '');

            // $response = Factory::payment()->page()->pay('123', md5('TEMP' . Carbon::now()->timestamp), '0.1', '');
            // echo $response->toMap(); exit;
            // return $response->toMap();
            return json_encode($response, JSON_UNESCAPED_UNICODE);
        } catch (Exception $e) {
            throw new LogicException($e->getMessage());
        }
    }
}
